<template>
  <div class="dashboard-container">
    <!-- 左侧上传图片和鸟类信息 -->
    <div class="upload-panel">
      <div class="panel-header">
        <h2>鸟类信息分析系统</h2>
      </div>

      <div class="panel-content">
        <!-- 上传区域 -->
        <div class="upload-area" @click="triggerUpload">
          <div v-if="!uploadedImage" class="upload-placeholder">
            <p>点击上传鸟类图片</p>
          </div>
          <img v-else :src="uploadedImage" alt="上传的鸟类图片" class="uploaded-image">
          <input
              type="file"
              ref="fileInput"
              @change="handleFileUpload"
              accept="image/*"
              style="display: none;"
          >
        </div>

        <!-- 鸟类信息区域 -->
        <div class="bird-info-section">
          <h3>鸟类详细信息</h3>

          <div class="bird-info-card">
            <div class="info-row">
              <span class="info-label">中文名称:</span>
              <span class="info-value">{{ currentBirdInfo.chineseName || '--' }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">英文名称:</span>
              <span class="info-value">{{ currentBirdInfo.englishName || '--' }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">鸟类形目:</span>
              <span class="info-value">{{ currentBirdInfo.order || '--' }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">分布区域:</span>
              <span class="info-value">{{ currentBirdInfo.distribution || '--' }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">生活习性:</span>
              <span class="info-value">{{ currentBirdInfo.habits || '--' }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">形态特征:</span>
              <span class="info-value">{{ currentBirdInfo.features || '--' }}</span>
            </div>

            <div class="info-row">
              <span class="info-label">保护等级:</span>
              <span class="info-value">{{ currentBirdInfo.protectionLevel || '--' }}</span>
            </div>
          </div>

          <!-- 移除保存按钮 -->
        </div>

        <!-- 历史记录 -->
        <div class="history-section">
          <h3>历史记录</h3>
          <div class="history-list">
            <div
                v-for="(record, index) in historyRecords"
                :key="index"
                class="history-item"
                @click="loadHistoryRecord(record)"
            >
              <div class="history-thumb">
                <img :src="record.image" alt="历史记录">
              </div>
              <div class="history-info">
                <div class="bird-name">{{ record.chineseName }}</div>
                <div class="record-date">{{ formatDate(record.date) }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧地图和控制面板 -->
    <div class="map-panel">
      <!-- 地图容器 -->
      <div class="map-container" ref="mapContainer"></div>

      <!-- 地图控制面板 -->
      <div class="map-control-panel">
        <!-- 数据卡片 -->
        <div class="data-cards">
          <div class="data-card">
            <div class="data-icon">
            </div>
            <div class="data-info">
              <h3>监测点数量</h3>
              <p class="data-value">{{ heatmapData.length }}</p>
            </div>
          </div>

          <div class="data-card">
            <div class="data-icon">
            </div>
            <div class="data-info">
              <h3>热力强度</h3>
              <p class="data-value">{{ heatmapIntensity }}</p>
            </div>
          </div>
        </div>

        <!-- 控制按钮 -->
        <div class="control-buttons">
          <button @click="showHeatmap" class="panel-btn">
            显示热力图
          </button>
          <button @click="hideHeatmap" class="panel-btn">
            隐藏热力图
          </button>
          <button @click="resetView" class="panel-btn">
            重置视图
          </button>
        </div>

      </div>

      <!-- 错误提示 -->
      <div v-if="error" class="error-message">
        <i class="fas fa-exclamation-triangle"></i>
        <p>{{ errorMessage }}</p>
        <button @click="retry" class="retry-btn">重新加载</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

// 响应式变量
const mapContainer = ref(null)
const map = ref(null)
const heatmapOverlay = ref(null)
const isMapLoaded = ref(false)
const error = ref(false)
const errorMessage = ref('')
const fileInput = ref(null)
const uploadedImage = ref(null)

// 鸟类信息
const currentBirdInfo = ref({
  chineseName: '',
  englishName: '',
  order: '',
  distribution: '',
  habits: '',
  features: '',
  protectionLevel: ''
})

// 历史记录
const historyRecords = ref([])

// 热力图数据
const heatmapData = ref([])
const heatmapIntensity = ref('中')

// 生成热力图数据
const generateHeatmapData = () => {
  const data = [];

  // 中国地图经纬度范围
  const chinaBounds = {
    minLng: 73.66, // 最西端
    maxLng: 135.05, // 最东端
    minLat: 18.15, // 最南端
    maxLat: 53.55  // 最北端
  };

  // 中国主要鸟类保护区坐标（模拟热点区域）
  const hotspots = [
    { lng: 116.4, lat: 39.9, radius: 3 }, // 北京周边
    { lng: 121.47, lat: 31.23, radius: 2 }, // 上海周边
    { lng: 113.53, lat: 22.3, radius: 1.5 }, // 广州周边
    { lng: 104.06, lat: 30.67, radius: 2 }, // 成都周边
    { lng: 87.62, lat: 43.82, radius: 4 }, // 新疆鸟类保护区
    { lng: 109.5, lat: 18.3, radius: 1.5 }, // 海南鸟类保护区
    { lng: 126.0, lat: 46.0, radius: 3 }, // 东北鸟类保护区
    { lng: 102.73, lat: 25.05, radius: 2.5 } // 云南鸟类保护区
  ];

  // 生成100个数据点
  for (let i = 0; i < 100; i++) {
    let lng, lat;

    // 80%的点在热点区域，20%的点随机分布在全国
    if (Math.random() < 0.8) {
      // 选择一个热点区域
      const hotspot = hotspots[Math.floor(Math.random() * hotspots.length)];

      // 在热点区域内生成随机点
      lng = hotspot.lng + (Math.random() - 0.5) * hotspot.radius;
      lat = hotspot.lat + (Math.random() - 0.5) * hotspot.radius;
    } else {
      // 在全国范围内随机分布
      lng = chinaBounds.minLng + Math.random() * (chinaBounds.maxLng - chinaBounds.minLng);
      lat = chinaBounds.minLat + Math.random() * (chinaBounds.maxLat - chinaBounds.minLat);
    }

    // 确保点在边界内
    lng = Math.max(chinaBounds.minLng, Math.min(chinaBounds.maxLng, lng));
    lat = Math.max(chinaBounds.minLat, Math.min(chinaBounds.maxLat, lat));

    // 随机计数（50-500），热点区域计数更高
    const baseCount = Math.floor(Math.random() * 450) + 50;
    const count = baseCount * (1 + Math.random()); // 热点区域计数增加

    data.push({ lng, lat, count });
  }

  heatmapData.value = data;

  // 计算热力强度
  const totalCount = data.reduce((sum, item) => sum + item.count, 0);
  const avgCount = totalCount / data.length;

  if (avgCount < 100) heatmapIntensity.value = '低';
  else if (avgCount < 200) heatmapIntensity.value = '中';
  else if (avgCount < 300) heatmapIntensity.value = '高';
  else heatmapIntensity.value = '极高';
};

// 触发文件上传
const triggerUpload = () => {
  fileInput.value.click()
}

// 处理文件上传
const handleFileUpload = (event) => {
  const file = event.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      uploadedImage.value = e.target.result

      // 模拟获取鸟类信息
      simulateBirdInfo()

      // 生成热力图数据
      generateHeatmapData()

      // 初始化地图
      initMap()

      // 自动保存鸟类信息
      saveBirdInfo()
    }
    reader.readAsDataURL(file)
  }
}

// 模拟获取鸟类信息
const simulateBirdInfo = () => {
  // 鸟类信息示例
  const birdExamples = [
    {
      chineseName: '丹顶鹤',
      englishName: 'Red-crowned Crane',
      order: '鹤形目',
      distribution: '中国东北、日本、朝鲜半岛',
      habits: '栖息于开阔平原、沼泽、湖泊、草地等环境',
      features: '体长约150厘米，全身白色，头顶红色，颈部和尾部黑色',
      protectionLevel: '国家一级保护动物'
    },
    {
      chineseName: '朱鹮',
      englishName: 'Crested Ibis',
      order: '鹳形目',
      distribution: '中国陕西、河南、浙江等地',
      habits: '栖息于海拔1200-1400米的疏林地带',
      features: '体长约80厘米，全身白色，翅膀和尾部粉红色',
      protectionLevel: '国家一级保护动物'
    },
    {
      chineseName: '绿孔雀',
      englishName: 'Green Peafowl',
      order: '鸡形目',
      distribution: '中国云南、东南亚地区',
      habits: '栖息于热带和亚热带常绿阔叶林和混交林',
      features: '雄鸟尾羽长而华丽，呈蓝绿色金属光泽',
      protectionLevel: '国家一级保护动物'
    }
  ]

  // 随机选择一个鸟类信息
  const randomIndex = Math.floor(Math.random() * birdExamples.length)
  currentBirdInfo.value = birdExamples[randomIndex]
}

// 保存鸟类信息到历史记录
const saveBirdInfo = () => {
  if (!uploadedImage.value) return;

  const record = {
    ...currentBirdInfo.value,
    image: uploadedImage.value,
    date: new Date(),
    heatmapData: heatmapData.value, // 保存热力图数据
    heatmapIntensity: heatmapIntensity.value // 保存热力强度
  }

  historyRecords.value.unshift(record)

  // 保存到localStorage
  localStorage.setItem('birdHistory', JSON.stringify(historyRecords.value))

  // 显示保存成功的提示
  showSaveNotification()
}


// 显示保存成功的通知
const showSaveNotification = () => {
  const notification = document.createElement('div')
  notification.className = 'save-notification'
  notification.innerHTML = `
    <i class="fas fa-check-circle"></i>
    <span>鸟类信息已自动保存</span>
  `
  document.body.appendChild(notification)

  // 3秒后移除通知
  setTimeout(() => {
    notification.style.opacity = '0'
    setTimeout(() => {
      document.body.removeChild(notification)
    }, 300)
  }, 3000)
}

// 加载历史记录
const loadHistoryRecord = (record) => {
  currentBirdInfo.value = {
    chineseName: record.chineseName,
    englishName: record.englishName,
    order: record.order,
    distribution: record.distribution,
    habits: record.habits,
    features: record.features,
    protectionLevel: record.protectionLevel
  }

  uploadedImage.value = record.image

  // 加载热力图数据
  heatmapData.value = record.heatmapData
  heatmapIntensity.value = record.heatmapIntensity

  // 重新渲染热力图
  renderHeatmap()
}

// 重新渲染热力图
const renderHeatmap = () => {
  if (!map.value || !window.BMapLib) {
    handleError('热力图库未加载', new Error('BMapLib未定义'))
    return
  }

  try {
    // 如果已有热力图覆盖物，先移除
    if (heatmapOverlay.value) {
      map.value.removeOverlay(heatmapOverlay.value)
    }

    // 创建新的热力图覆盖物
    heatmapOverlay.value = new BMapLib.HeatmapOverlay({
      radius: 25,
      color: [
        '#1b5e20',
        '#4caf50',
        '#cddc39',
        '#ff9800',
        '#f44336',
        '#b71c1c'
      ]
    })

    // 将热力图添加到地图
    map.value.addOverlay(heatmapOverlay.value)

    // 设置热力图数据
    const points = heatmapData.value.map(item => {
      return {
        lng: item.lng,
        lat: item.lat,
        count: item.count
      }
    })

    heatmapOverlay.value.setDataSet({
      data: points,
      max: 500
    })

    // 默认显示热力图
    heatmapOverlay.value.show()
  } catch (err) {
    handleError('热力图渲染失败', err)
  }
}

// 格式化日期
const formatDate = (date) => {
  return new Date(date).toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  })
}

// 加载百度地图API
const loadBMap = () => {
  return new Promise((resolve, reject) => {
    if (window.BMap) {
      resolve(window.BMap)
      return
    }

    window.onBMapCallback = function () {
      if (window.BMap) {
        resolve(window.BMap)
      } else {
        reject(new Error('百度地图主库加载失败'))
      }
    }

    const script = document.createElement('script')
    script.src = `https://api.map.baidu.com/api?v=3.0&ak=I5iKNMdJhD7cWCz2QoQhoK8Eb9M61YOS&callback=onBMapCallback`
    script.onerror = (err) => {
      reject(new Error('百度地图脚本加载失败'))
    }
    document.head.appendChild(script)
  })
}

// 加载热力图库
const loadHeatmapLib = () => {
  return new Promise((resolve, reject) => {
    if (window.BMapLib) {
      resolve()
      return
    }

    const script = document.createElement('script')
    script.src = 'https://api.map.baidu.com/library/Heatmap/2.0/src/Heatmap_min.js'
    script.onload = resolve
    script.onerror = () => reject(new Error('热力图库加载失败'))
    document.head.appendChild(script)
  })
}

// 初始化地图
const initMap = async () => {
  try {
    error.value = false
    isMapLoaded.value = false

    // 加载百度地图主库
    const BMap = await loadBMap()

    // 加载热力图库
    await loadHeatmapLib()

    if (mapContainer.value) {
      // 创建地图实例
      map.value = new BMap.Map(mapContainer.value)

      // 设置中心点和缩放级别
      const point = new BMap.Point(116.404, 39.915)
      map.value.centerAndZoom(point, 5)

      // 添加控件
      map.value.addControl(new BMap.NavigationControl())
      map.value.addControl(new BMap.ScaleControl())
      map.value.addControl(new BMap.OverviewMapControl())

      // 启用滚轮缩放
      map.value.enableScrollWheelZoom(true)

      // 渲染热力图
      renderHeatmap()

      isMapLoaded.value = true
    }
  } catch (err) {
    handleError('百度地图加载失败', err)
  }
}


// 初始化热力图
const initHeatmap = () => {
  if (!map.value || !window.BMapLib) {
    handleError('热力图库未加载', new Error('BMapLib未定义'))
    return
  }

  try {
    // 创建热力图覆盖物
    heatmapOverlay.value = new BMapLib.HeatmapOverlay({
      radius: 25,
      color: [
        '#1b5e20',
        '#4caf50',
        '#cddc39',
        '#ff9800',
        '#f44336',
        '#b71c1c'
      ]
    })

    // 将热力图添加到地图
    map.value.addOverlay(heatmapOverlay.value)

    // 设置热力图数据
    const points = heatmapData.value.map(item => {
      return {
        lng: item.lng,
        lat: item.lat,
        count: item.count
      }
    })

    heatmapOverlay.value.setDataSet({
      data: points,
      max: 500
    })

    // 默认显示热力图
    heatmapOverlay.value.show()
  } catch (err) {
    handleError('热力图初始化失败', err)
  }
}

// 错误处理
const handleError = (message, err) => {
  console.error(message, err)
  error.value = true
  errorMessage.value = `${message}: ${err.message || '未知错误'}`
}

// 重新加载
const retry = () => {
  error.value = false
  initMap()
}

// 显示热力图
const showHeatmap = () => {
  if (heatmapOverlay.value) {
    heatmapOverlay.value.show()
  }
}

// 隐藏热力图
const hideHeatmap = () => {
  if (heatmapOverlay.value) {
    heatmapOverlay.value.hide()
  }
}

// 重置视图
const resetView = () => {
  if (map.value) {
    const point = new BMap.Point(116.404, 39.915)
    map.value.centerAndZoom(point, 5)
  }
}

// 组件挂载时初始化地图
onMounted(() => {
  initMap()
  // 加载历史记录
  const savedHistory = localStorage.getItem('birdHistory')
  if (savedHistory) {
    try {
      historyRecords.value = JSON.parse(savedHistory)
    } catch (e) {
      console.error('加载历史记录失败', e)
    }
  }
})

// 组件卸载时销毁地图
onUnmounted(() => {
  // 初始化地图但不立即渲染热力图
  initMap()

  // 加载历史记录
  const savedHistory = localStorage.getItem('birdHistory')
  if (savedHistory) {
    try {
      historyRecords.value = JSON.parse(savedHistory)
    } catch (e) {
      console.error('加载历史记录失败', e)
    }
  }
  if (map.value) {
    map.value = null
  }
})
</script>

<style scoped>
.dashboard-container {
  display: flex;
  width: 100%;
  height: 100vh;
  background: #f5f9f5;
}

/* 左侧上传面板样式 */
.upload-panel {
  width: 30%;
  min-width: 300px;
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.panel-header {
  background: linear-gradient(135deg, #2e8b57, #3cb371);
  color: white;
  padding: 20px;
  text-align: center;
}

.panel-header h2 {
  margin: 0;
  font-size: 1.5rem;
}

.panel-content {
  padding: 20px;
  flex: 1;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.upload-area {
  height: 250px;
  border: 2px dashed #3cb371;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #f0f8f0;
}

.upload-area:hover {
  border-color: #2e8b57;
  background: #e6f5e6;
}

.upload-placeholder {
  text-align: center;
  color: #556b2f;
}

.upload-placeholder i {
  font-size: 48px;
  color: #3cb371;
  margin-bottom: 15px;
}

.upload-placeholder p {
  margin: 0;
  font-size: 16px;
}

.uploaded-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.bird-info-section {
  background: #f8fcf8;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.bird-info-section h3 {
  color: #2e8b57;
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e1f0e1;
}

.bird-info-card {
  background: white;
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.info-row {
  display: flex;
  margin-bottom: 12px;
  padding-bottom: 12px;
  border-bottom: 1px dashed #e0e0e0;
}

.info-row:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.info-label {
  width: 80px;
  font-weight: 600;
  color: #556b2f;
}

.info-value {
  flex: 1;
  color: #333;
}

.history-section {
  background: #f8fcf8;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  flex: 1;
  display: flex;
  flex-direction: column;
}

.history-section h3 {
  color: #2e8b57;
  margin-top: 0;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e1f0e1;
}

.history-list {
  flex: 1;
  overflow-y: auto;
}

.history-item {
  display: flex;
  padding: 10px;
  border-radius: 8px;
  margin-bottom: 10px;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  cursor: pointer;
  transition: all 0.2s ease;
}

.history-item:hover {
  background: #f0f8f0;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.history-thumb {
  width: 60px;
  height: 60px;
  border-radius: 6px;
  overflow: hidden;
  margin-right: 12px;
}

.history-thumb img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.history-info {
  flex: 1;
}

.bird-name {
  font-weight: 600;
  color: #2e8b57;
  margin-bottom: 5px;
}

.record-date {
  font-size: 12px;
  color: #777;
}

/* 右侧地图面板样式 */
.map-panel {
  flex: 1;
  position: relative;
  background: #e6f5e6;
  display: flex;
  flex-direction: column;
}

.map-container {
  flex: 1;
  width: 100%;
}

.map-control-panel {
  background: white;
  padding: 15px;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.data-cards {
  display: flex;
  gap: 15px;
  flex: 1;
}

.data-card {
  display: flex;
  align-items: center;
  background: #f0f8f0;
  border-radius: 10px;
  padding: 15px;
  flex: 1;
  min-width: 150px;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}

.data-icon {
  width: 40px;
  height: 40px;
  background: linear-gradient(135deg, #2e8b57, #3cb371);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.data-icon i {
  font-size: 18px;
  color: white;
}

.data-info h3 {
  margin: 0 0 5px 0;
  font-size: 0.9rem;
  color: #556b2f;
}

.data-value {
  margin: 0;
  font-size: 1.2rem;
  font-weight: bold;
  color: #2e8b57;
}

.control-buttons {
  display: flex;
  gap: 10px;
  flex: 1;
}

.panel-btn {
  background: #3cb371;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 15px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s ease;
  flex: 1;
  min-width: 120px;
}

.panel-btn:hover {
  background: #2e8b57;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.panel-btn i {
  font-size: 16px;
}

.error-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: white;
  padding: 25px;
  border-radius: 10px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
  text-align: center;
  z-index: 1001;
  max-width: 80%;
}

.error-message i {
  font-size: 2.5rem;
  color: #e74c3c;
  margin-bottom: 15px;
}

.error-message p {
  margin: 0 0 20px 0;
  font-size: 1.1rem;
  color: #495057;
}

.retry-btn {
  background: #3cb371;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.retry-btn:hover {
  background: #2e8b57;
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}
</style>

<style>
/* 添加保存通知样式 */
.save-notification {
  position: fixed;
  bottom: 20px;
  right: 20px;
  background: #4caf50;
  color: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  gap: 10px;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
  transition: opacity 0.3s ease;
}

.save-notification i {
  font-size: 20px;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>